package com.olts.controller;

import com.olts.service.IFileService;
import com.olts.service.IOltsUserService;
import com.olts.service.OltsScoreService;
import com.olts.service.impl.OltsUserServiceImpl;
import com.olts.vo.Msg;
import com.olts.vo.OltsUser;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2018/10/10.
 */
@Controller
@RequestMapping("/file")
public class FileController implements ServletContextAware {

    @Resource
    IFileService fileService;

    @Resource
    IOltsUserService oltsUserService;

    ServletContext servletContext;
    static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");

    @RequestMapping(value = "/changePath",method = RequestMethod.POST)
    @ResponseBody
    public Msg uploadPath(@RequestParam("file") CommonsMultipartFile file, Integer id) {
        Msg msg = new Msg();
        // 得到上传的文件
        FileItem fileItem = file.getFileItem();

        // 获得文件MIME类型: image/jpg, text/html, text/css, text/js
        String contentType = file.getContentType();

        // 上传文件的原始文件名，注意多人上传可会有同名的文件
        String originalFilename = file.getOriginalFilename();

        //生成上传后的新文件名：原文件名_YYYYMMDD_HHMMSS.txt
        String destFileName = StringUtils.substringBefore(originalFilename,".")
                + "_"+ sdf.format(new Date()) + "."+StringUtils.substringAfter(originalFilename, ".");

        // jsp: application = ServletContext
        String realPath = this.servletContext.getRealPath("/upload");
        File destFile = new File(realPath, destFileName);
        try {
            fileItem.write(destFile);
            int i = this.fileService.updatePath(id,destFileName);
            if (i==1) {
                msg.setPath(destFileName);
                msg.setMsg(true);
            }else {
                msg.setMsg(false);
            }
        } catch (Exception e) {
            msg.setMsg(false);
        }
        return msg;
    }

    @RequestMapping(value = "/changePathMy",method = RequestMethod.POST)
    @ResponseBody
    public Msg changePathMy(@RequestParam("file") CommonsMultipartFile file, Integer id,HttpSession session) {
        Msg msg = new Msg();
        // 得到上传的文件
        FileItem fileItem = file.getFileItem();

        // 获得文件MIME类型: image/jpg, text/html, text/css, text/js
        String contentType = file.getContentType();

        // 上传文件的原始文件名，注意多人上传可会有同名的文件
        String originalFilename = file.getOriginalFilename();

        //生成上传后的新文件名：原文件名_YYYYMMDD_HHMMSS.txt
        String destFileName = StringUtils.substringBefore(originalFilename,".")
                + "_"+ sdf.format(new Date()) + "."+StringUtils.substringAfter(originalFilename, ".");

        // jsp: application = ServletContext
        String realPath = this.servletContext.getRealPath("/upload");
        File destFile = new File(realPath, destFileName);
        try {
            fileItem.write(destFile);
            int i = this.fileService.updatePath(id,destFileName);
            if (i==1) {
                session.removeAttribute("logUser");
                session.setAttribute("logUser",this.oltsUserService.selectById(id));
                msg.setPath(destFileName);
                msg.setMsg(true);
            }else {
                msg.setMsg(false);
            }
        } catch (Exception e) {
            msg.setMsg(false);
        }
        return msg;
    }

    @RequestMapping(value = "/addStuALL",method = RequestMethod.POST)
    @ResponseBody
    public Msg uploadExl(@RequestParam("file") CommonsMultipartFile file) {
        Msg msg = new Msg();
        // 得到上传的文件
        FileItem fileItem = file.getFileItem();
        InputStream is = null;
        try {
            is = fileItem.getInputStream();
        } catch (FileNotFoundException e) {
            msg.setPath("找不到EXL文件");
            msg.setMsg(false);
        } catch (IOException e) {
            msg.setPath("找不到EXL文件");
            msg.setMsg(false);
        }

        try {
            // 创建工作本
            Workbook wb = new HSSFWorkbook(is);
            //得到第一个工作表
            Sheet sheet = wb.getSheetAt(0);
            //得到工作表中的行数
            int numberOfRows = sheet.getPhysicalNumberOfRows();
            List<OltsUser> users = new ArrayList<>();
            for (int rowIdx = 1; rowIdx < numberOfRows; rowIdx++) {
                OltsUser user = new OltsUser();
                //得到每一行
                Row row = sheet.getRow(rowIdx);
                //得到每一个单元格
                Cell cell = null;
                cell = row.getCell(1);
                if (cell.getStringCellValue().trim().length()<1) {
                    break;
                }
                user.setUserName(cell.getStringCellValue());

                cell = row.getCell(2);
                user.setStuNo(cell.getStringCellValue());

                cell = row.getCell(3);
                user.setIdCardNo(cell.getStringCellValue());
                if(cell.getStringCellValue() != null) {
                    if (cell.getStringCellValue().trim().length() > 12){
                        user.setPassWord(cell.getStringCellValue().substring(12));
                    }else {
                        user.setPassWord("123456");
                    }
                }

                cell = row.getCell(4);
                user.setEduBackground(cell.getStringCellValue());

                cell = row.getCell(5);
                user.setMarjor(cell.getStringCellValue());

                cell = row.getCell(6);
                user.setMobile(cell.getStringCellValue());

                cell = row.getCell(7);
                user.setQq(cell.getStringCellValue());
                users.add(user);
            }
            int i = this.fileService.insertUserAll(users);
            if (i > 0) {
                msg.setPath("上传成功");
                msg.setMsg(true);
            }
        } catch (IOException e) {
            msg.setPath("读取EXL文件出错");
            msg.setMsg(false);
        }
        return msg;
    }

    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }
}
